//
// Created by Yun on 2025/2/26.
//

#include "dev_tim.h"

/*---------------------- 全局变量定义 ----------------------*/
Dev_Tim_Cfg_TypeDef* stDevTimCfgNodeHead; /*!< UART设备链表头指针 */

/*---------------------- 静态函数 ----------------------*/
/**
 * @brief  超时回调函数
 * @param  pvHwCfg: 硬件配置
 * @retval 无
 */
static void Dev_Tim_Callback(void* pvHwCfg)
{
    Dev_Tim_Cfg_TypeDef* pstCurrent = stDevTimCfgNodeHead;
    while(pstCurrent != NULL)
    {
        if(pstCurrent->u8InitState!= DEV_IS_INIT ||
           pstCurrent->u8RunState != DEV_IDLE     ) {
            pstCurrent = pstCurrent->pstNext;
            continue;
        }

        DEV_BUSY(pstCurrent);

        if(pstCurrent->pHwCfg == pvHwCfg)
        {
            if(pstCurrent->u8CurTick < pstCurrent->u8Timeout)
            {
                pstCurrent->u8CurTick++;
                pstCurrent = pstCurrent->pstNext;
                continue;
            }

            pstCurrent->u8CurTick = 0;
            DEV_PUSH_EVENT(EVENT_DEV_TIM_TIMOUT, pstCurrent, pstCurrent);
        }
        pstCurrent = pstCurrent->pstNext;
    }
}

uint8_t Dev_Tim_Register(Dev_Tim_Cfg_TypeDef* pstConfig,
                         void* pHwCfg,
                         Tim_Interface_TypeDef* pstDevTimInterface)
{
    /* 参数有效性检查 */
    if (!pstConfig || !pHwCfg || !pstDevTimInterface) {
        return DEV_ERROR;
    }

    pstConfig->u8InitState = DEV_NOT_INIT;

    /* 配置设备参数 */
    pstConfig->pHwCfg = pHwCfg;
    pstConfig->pstDevTimInterface = pstDevTimInterface;
    pstConfig->u8CurTick = 0;

    /* 执行硬件初始化 */
    CHECK_DEV_STATUS(pstConfig->pstDevTimInterface->Init(pHwCfg,
                                                         Dev_Tim_Callback));

    /* 链表头部插入 */
    pstConfig->pstNext = stDevTimCfgNodeHead;
    stDevTimCfgNodeHead = pstConfig;

    DEV_INIT(pstConfig);
    return DEV_OK;
}

uint8_t Dev_Tim_En(Dev_Tim_Cfg_TypeDef* pstConfig,
                   uint8_t u8State)
{
    if(!pstConfig) return DEV_ERROR;

    CHECK_DEV_ENABLE(pstConfig);
    DEV_BUSY(pstConfig);

    CHECK_DEV_STATUS(pstConfig->pstDevTimInterface->Enable(pstConfig->pHwCfg, u8State));
    return DEV_OK;
}
